/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.academy.web.action.course;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ar.uba.fi.posgrado.academy.model.Course;
import ar.uba.fi.posgrado.academy.model.Instalment;
import ar.uba.fi.posgrado.academy.service.CourseService;
import ar.uba.fi.posgrado.academy.web.form.course.InstalmentForm;
import ar.uba.fi.posgrado.economy.service.DebtService;
import ar.uba.fi.posgrado.economy.web.util.DebtTypeToLabelValueTransformer;

/**
 * Action que muestra la pantalla para establecer las {@link Instalment cuotas}
 * de un curso.<br>
 * 
 * @author ariel.piechotka
 */
public class ShowInstalmentsAction extends Action {
	/** Logger */
	private static Logger logger = Logger
			.getLogger(ShowInstalmentsAction.class);

	private CourseService courseService;

	private DebtService debtService;

	public void setCourseService(CourseService courseService) {
		this.courseService = courseService;
	}

	public void setDebtService(DebtService debtService) {
		this.debtService = debtService;
	}

	/**
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping,
	 *      org.apache.struts.action.ActionForm,
	 *      javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (logger.isDebugEnabled())
			logger.debug("Por mostrar la pantalla de seteo de cuotas...");

		InstalmentForm form = (InstalmentForm) actionForm;
		boolean reloadingForm = request.getHeader("referer").matches(
				".*showInstalments.*");
		if (!reloadingForm) { // Null al cargar desde otros forms, not-null en
			// los reloads
			Long id = Long.parseLong(request.getParameter("id"));
			Course course = courseService.getById(id);
			form.setCourse(course);
			form.setCourseId(id);

			Set<Instalment> instalments = form.getCourse().getInstalments();
			short qtyInstalments = (short) instalments.size();

			for (Instalment instalment : instalments)
				if (instalment.getInstNumber() == 0) {
					form.setRegistrationFeeValue(instalment.getValue());
					qtyInstalments -= 1; // La matricula no cuenta como cuota
					// en el form
				}

			if (qtyInstalments == 0)
				qtyInstalments = Instalment.DEFAULT_QTY_INSTALMENTS;
			form.setQtyInstalments(qtyInstalments);
			form.setQtyRegFees((short)form.getCourse().getQtyRegistrationFees());

			String[] instalmentsValues = new String[Instalment.MAX_QTY_INSTALMENTS];
			for (Instalment instalment : instalments)
				if (instalment.getInstNumber() != 0)
					instalmentsValues[instalment.getInstNumber() - 1] = ((Double) instalment
							.getValue()).toString();
			form.setInstalmentsValues(instalmentsValues);
		}

		// Carga los tipos de deuda disponibles
		List debtTypes = debtService.getAllDebtTypes();
		// Aca se cambia el tipo de la collection, por eso no esta tipada
		CollectionUtils.transform(debtTypes,
				new DebtTypeToLabelValueTransformer());
		form.setDebtTypeOptions(debtTypes);

		logger.info("Mostrar pantalla seteo cuotas finalizado");
		return mapping.findForward("success");
	}
}
